//
//  addGroupGuestView.m
//  QRMaster
//
//  Created by myApple on 15/10/27.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "addGroupGuestView.h"
#import "GroupGuestLogic.h"
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
#import "PromptInfoView.h"
#import "RequestNetWork.h"
#import "GuestModel.h"
#import "GuestManagerViewController.h"
#import "validateInputValue.h"
#import "MBProgressHUD.h"
#import "GroupGuestLogic.h"

#define fontSize [UIFont systemFontOfSize:14.0]
#define ViewHeigth  50

@interface addGroupGuestView ()<ABPeoplePickerNavigationControllerDelegate,UITextFieldDelegate>
{
    UIView * editingView;
    UITextField * telePhoneTextField;
    UITextField * nameTextField;
    UITextField * ceritificateTextField;
    UIButton * manBtn;
    UIButton * womanBtn;
    UIImageView * manView;
    UIImageView * womanView;
    NSString * sexFlag;
    UIButton * roomBtn;
    NSMutableDictionary * saveDict;
    
    UIImageView * editImgView;
    
    UIActivityIndicatorView * _activityIndicator;
}

@end

@implementation addGroupGuestView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hiddenKeyboard) name:@"KCHiddenKeyBoardNotification" object:nil];
        [self prepareActivityIndicator];
        [self prepareHeadView];
        [self prepareEditingView];
        saveDict = [[NSMutableDictionary alloc]init];
        sexFlag = @"1";
    }
    
    return self;
}

-(void)prepareHeadView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float x = 0;
    float y = 20;
    float width = ScreenWidth;
    float height = 44;
    
    UIView * topView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    topView.backgroundColor = [UIColor blackColor];
    [self addSubview:topView];
    
    x = 10;
    y = 2;
    height = 40;
    width = 40;
    UIImage * backImage = [UIImage imageNamed:@"24X24"];
    UIButton * backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(x, y, width, height);
    [backBtn setImage:backImage forState:0];
    [backBtn addTarget:self action:@selector(BackClick) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:backBtn];
    
    x = ScreenWidth / 2.0 - 100;
    y = 5;
    width = 200;
    height = 34;
    UILabel * titleNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    titleNameLabel.text = NSLocalizedString(@"addGroupGuest", nil);
    titleNameLabel.textColor = [UIColor whiteColor];
    titleNameLabel.textAlignment = NSTextAlignmentCenter;
    titleNameLabel.font = [UIFont systemFontOfSize:16.0];
    [topView addSubview:titleNameLabel];
    
    //编辑
    x = ScreenWidth - 60;
    width = 40;
    y = 2;
    height = 40;
    UIView * editBackView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    [topView addSubview:editBackView];
    x = 10;
    width = 20;
    height = 20;
    y = 10;
    editImgView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    editImgView.image = [UIImage imageNamed:@"ic_save"];
    editImgView.userInteractionEnabled = YES;
    [editBackView addSubview:editImgView];
    UITapGestureRecognizer * editTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(saveClick)];
    [editBackView addGestureRecognizer:editTap];
}

-(void)prepareEditingView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
    float x = 0;
    float y = 64;
    float width = ScreenWidth;
    float height = ScreenHeight - y;
    
    editingView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    editingView.backgroundColor = RGBA(237, 238, 241, 1);
    [self addSubview:editingView];
    
    //手机号码
    x = 10;
    y = 5;
    width = ScreenWidth - x - 5;
    height = ViewHeigth;
    UIView * telePhoneView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    telePhoneView.backgroundColor = RGBA(248, 248, 248, 1);
    [editingView addSubview:telePhoneView];
    
    x = 10;
    y = 15;
    width = 60;
    height = 20;
    UILabel * telePhoenLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    telePhoenLabel.text = NSLocalizedString(@"account", nil);
    telePhoenLabel.font = fontSize;
    [telePhoneView addSubview:telePhoenLabel];
    
    x = 100;
    y = 10;
    width = telePhoneView.frame.size.width - x ;
    height = 30;
    telePhoneTextField = [[UITextField alloc]initWithFrame:CGRectMake(x, y, width, height)];
    telePhoneTextField.font = [UIFont systemFontOfSize:14.0];
    telePhoneTextField.borderStyle = UITextBorderStyleNone;
    telePhoneTextField.placeholder = NSLocalizedString(@"mobileOrEmail", nil);
    [telePhoneTextField becomeFirstResponder];
    [telePhoneView addSubview:telePhoneTextField];
    
    x = telePhoneView.frame.size.width - 50;
    y = 0;
    width = 50;
    height = 50;
    UIButton * addAddressTelePhoneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addAddressTelePhoneBtn.frame = CGRectMake(x, y, width, height);
    [addAddressTelePhoneBtn setBackgroundColor:[UIColor greenColor]];
    [addAddressTelePhoneBtn setBackgroundImage:nil forState:0];
    [addAddressTelePhoneBtn addTarget:self action:@selector(addTelePhone) forControlEvents:UIControlEventTouchUpInside];
    [telePhoneView addSubview:addAddressTelePhoneBtn];
    
    UIImageView * adderssImgView = [[UIImageView alloc]initWithFrame:CGRectMake(10,10, 30, 30)];
    adderssImgView.image = [UIImage imageNamed:@"ic_txl"];
    [addAddressTelePhoneBtn addSubview:adderssImgView];
    
    //姓名
    x = 10;
    y = telePhoneView.frame.size.height + telePhoneView.frame.origin.y + 5;
    width = ScreenWidth - x - 5;
    height = ViewHeigth;
    UIView * nameView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    nameView.backgroundColor = RGBA(248, 248, 248, 1);
    [editingView addSubview:nameView];
    
    x = 10;
    y = 15;
    width = 40;
    height = 20;
    UILabel * editUserNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    editUserNameLabel.text =  NSLocalizedString(@"userName", nil);
    editUserNameLabel.font = fontSize;
    [nameView addSubview:editUserNameLabel];
    
    x = 100;
    y = 10;
    width = nameView.frame.size.width - x ;
    height = 30;
    nameTextField = [[UITextField alloc]initWithFrame:CGRectMake(x, y, width, height)];
    nameTextField.font = [UIFont systemFontOfSize:14.0];
    nameTextField.borderStyle = UITextBorderStyleNone;
    [nameView addSubview:nameTextField];
    
    //身份证
    x = 10;
    y = nameView.frame.size.height + nameView.frame.origin.y + 5;
    width = ScreenWidth - x - 5;
    height = ViewHeigth;
    UIView * certificateView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    certificateView.backgroundColor = RGBA(248, 248, 248, 1);
    [editingView addSubview:certificateView];
    
    x = 10;
    y = 15;
    width = 60;
    height = 20;
    UILabel * certificateTextLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    certificateTextLabel.text = NSLocalizedString(@"certificate", nil);
    certificateTextLabel.font = fontSize;
    [certificateView addSubview:certificateTextLabel];
    
    x = 100;
    y = 10;
    width = nameView.frame.size.width - x ;
    height = 30;
    ceritificateTextField = [[UITextField alloc]initWithFrame:CGRectMake(x, y, width, height)];
    ceritificateTextField.font = [UIFont systemFontOfSize:14.0];
    ceritificateTextField.borderStyle = UITextBorderStyleNone;
    [certificateView addSubview:ceritificateTextField];
    
    //性别
    x = 10;
    y = 5 + certificateView.frame.size.height + certificateView.frame.origin.y;
    width = ScreenWidth - x - 5;
    height = ViewHeigth;
    UIView * sexView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    sexView.backgroundColor = RGBA(248, 248, 248, 1);
    [editingView addSubview:sexView];
    
    
    x = 10;
    y = 15;
    width = 60;
    height = 20;
    UILabel * editSexLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    editSexLabel.text = NSLocalizedString(@"sex", nil);
    editSexLabel.font = fontSize;
    [sexView addSubview:editSexLabel];
    
    x = 100;
    y = 0;
    width = 40;
    height = 50;
    manView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    [sexView addSubview:manView];
    manView.userInteractionEnabled = YES;
    UITapGestureRecognizer * manTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(manClick)];
    [manView addGestureRecognizer:manTap];
    
    x = 100;
    y = 15;
    width = 20;
    height = 20;
    manBtn = [[UIButton alloc]initWithFrame:CGRectMake(x, y, width, height)];
    [manBtn setBackgroundImage:[UIImage imageNamed:@"36_1"] forState:0];
    [manBtn setBackgroundImage:[UIImage imageNamed:@"36_2"] forState:UIControlStateSelected];
    [manBtn addTarget:self action:@selector(manClick) forControlEvents:UIControlEventTouchUpInside];
    manBtn.selected = YES;
    [sexView addSubview:manBtn];
    
    x = 140;
    height = 20;
    UILabel * manLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, 40, height)];
    manLabel.text =  NSLocalizedString(@"man", nil);
    manLabel.font = fontSize;
    [sexView addSubview:manLabel];
    
    x = 180;
    y = 0;
    width = 40;
    height = ViewHeigth;
    womanView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    [sexView addSubview:womanView];
    womanView.userInteractionEnabled = YES;
    UITapGestureRecognizer * womanTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(womanClick)];
    [womanView addGestureRecognizer:womanTap];
    
    x += 10;
    y += 15;
    width = 20;
    height = 20;
    womanBtn = [[UIButton alloc]initWithFrame:CGRectMake(x, y, width, height)];
    [womanBtn setBackgroundImage:[UIImage imageNamed:@"36_1"] forState:0];
    [womanBtn setBackgroundImage:[UIImage imageNamed:@"36_2"] forState:UIControlStateSelected];
    [womanBtn addTarget:self action:@selector(womanClick) forControlEvents:UIControlEventTouchUpInside];
    [sexView addSubview:womanBtn];
    
    x = 220;
    height = 20;
    UILabel * womanLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, 60, height)];
    womanLabel.text =  NSLocalizedString(@"woman", nil);
    womanLabel.font = fontSize;
    [sexView addSubview:womanLabel];
    
    UITapGestureRecognizer * guestTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(resignClick)];
    [self addGestureRecognizer:guestTap];
}

//初始化风火轮
-(void)prepareActivityIndicator
{
    _activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    _activityIndicator.frame = CGRectMake(self.frame.size.width / 2.0 -15, self.frame.size.height/2.0 - 15, 30, 30);
    [self addSubview:_activityIndicator];
}

#pragma mark -- 从通讯录添加职员
-(void)addTelePhone
{
    ABPeoplePickerNavigationController * peoplePicker = [[ABPeoplePickerNavigationController alloc]init];
    peoplePicker.peoplePickerDelegate = self;
    if (_delegate && [_delegate respondsToSelector:@selector(addGuestInfoViewSendTo:)]) {
        [_delegate addGuestInfoViewSendTo:peoplePicker];
    }
}

#pragma mark -- ABPeoplePickerNavigationControllerDelegate
-(void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person
{
    ABMutableMultiValueRef phoneMult = ABRecordCopyValue(person, kABPersonPhoneProperty);
    NSString * fisrtName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
    NSString * lastName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
    if (fisrtName == nil) {
        fisrtName = @"";
    }
    if (lastName == nil) {
        lastName = @"";
    }
    nameTextField.text = [NSString stringWithFormat:@"%@%@",lastName,fisrtName];
    
    NSMutableArray *phones = [NSMutableArray arrayWithCapacity:0];
    for (int i = 0; i < ABMultiValueGetCount(phoneMult); i ++) {
        NSString * aphone = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phoneMult, i);
        [phones addObject:aphone];
    }
    if (phones.count > 0) {
        telePhoneTextField.text = [phones objectAtIndex:0];
        telePhoneTextField.text = [telePhoneTextField.text stringByReplacingOccurrencesOfString:@"-" withString:@""];
    }
    
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -- ABPeoplePickerNavigationControllerDelegate
-(void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
{
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
}

//2_0到8_0系统使用的方法
-(BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
    ABMutableMultiValueRef phoneMult = ABRecordCopyValue(person, kABPersonPhoneProperty);
    NSString * fisrtName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
    NSString * lastName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
    if (fisrtName == nil) {
        fisrtName = @"";
    }
    if (lastName == nil) {
        lastName = @"";
    }
    nameTextField.text = [NSString stringWithFormat:@"%@%@",lastName,fisrtName];
    
    NSMutableArray *phones = [NSMutableArray arrayWithCapacity:0];
    for (int i = 0; i < ABMultiValueGetCount(phoneMult); i ++) {
        NSString * aphone = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phoneMult, i);
        [phones addObject:aphone];
    }
    if (phones.count > 0) {
        telePhoneTextField.text = [phones objectAtIndex:0];
        telePhoneTextField.text = [telePhoneTextField.text stringByReplacingOccurrencesOfString:@"-" withString:@""];
    }
    
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
    return NO;
}



-(void)resignClick
{
    [nameTextField resignFirstResponder];
    [telePhoneTextField resignFirstResponder];
    [ceritificateTextField resignFirstResponder];
}

-(void)saveClick
{
    [self resignClick];
    if (telePhoneTextField.text.length == 0) {
        [PromptInfoView showMessage:NSLocalizedString(@"errorAccount", nil) superView:self];
        return;
    }
    if(![validateInputValue telePhoneValidate:telePhoneTextField.text] && ![validateInputValue validateEmail:telePhoneTextField.text])
    {
        [PromptInfoView showMessage:NSLocalizedString(@"AccountError", nil) superView:self];
        return;
    }
    if (nameTextField.text.length < 1 || nameTextField.text.length > 20) {
        [PromptInfoView showMessage:NSLocalizedString(@"userNameLength", nil) superView:self];
        return;
    }

    NSString * locaString = NSLocalizedString(@"sureAdd", nil);
    NSString * telePhoneString = [NSString stringWithFormat:@"%@%@？",locaString,telePhoneTextField.text];
    UIAlertView * alert = [[UIAlertView alloc]initWithTitle:nil message:telePhoneString delegate:self cancelButtonTitle:NSLocalizedString(@"alterCancel", nil) otherButtonTitles:NSLocalizedString(@"alterSure", nil), nil];
    [alert show];
}


#pragma mark -- alertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [self saveGuestInfo];
    }
}

-(void)saveGuestInfo
{
    [MBProgressHUD showHUDAddedTo:self animated:YES];
    
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    __block NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:_communityId forKey:@"communityId"];
    [postDict setValue:_groupId forKey:@"groupId"];
    [postDict setValue:telePhoneTextField.text  forKey:@"account"];
    [postDict setValue:nameTextField.text forKey:@"name"];
    [postDict setValue:ceritificateTextField.text forKey:@"identity"];
    [postDict setValue:sexFlag forKey:@"gender"];
    if([self getTimestamp:_groupId] != nil)
    {
        [postDict setValue:[self getTimestamp:_groupId] forKey:@"timestamp"];
    }
    else
    {
        [postDict setValue:@"" forKey:@"timestamp"];
    }
    __weak addGroupGuestView * weakSelf = self;
    RequestNetWork * rnw = [[RequestNetWork alloc]init];
    [rnw initWithPath:POST(ADDGROUPCLIENT) params:postDict block:^(id downLoadData, id error)
     {
         if ([downLoadData objectForKey:@"cache"] ) {
             if ([[[downLoadData objectForKey:@"cache"] objectForKey:@"status"]integerValue] == 0)
             {
                 GuestModel * model = [[GuestModel alloc]init];
                 NSMutableDictionary *data = [[NSMutableDictionary alloc]init];
                 data = [[downLoadData objectForKey:@"cache"] objectForKey:@"data"];
                 model.email = [data objectForKey:@"email"];
                 model.firstChar = [data objectForKey:@"firstchar"];
                 model.sex = [data objectForKey:@"gender"];
                 model.headUrl = [data objectForKey:@"headurl"];
                 model.guestid = [data objectForKey:@"id"];
                 model.certificaties = [data objectForKey:@"identity"];
                 model.telePhone = [data objectForKey:@"mobile"];
                 model.guestName= [data objectForKey:@"name"];
                 model.isGroupManager = @"0";
                 NSMutableArray * guestArray = [[NSMutableArray alloc]init];
                 [guestArray addObject:model];
                 
                 GroupGuestLogic *groupGuest = [[GroupGuestLogic alloc]init];
                 [groupGuest insertGroupGuestInfo:model groupName:_groupName groupStartTime:nil groupEndTime:nil groupId:_groupId];
                 
                 [weakSelf updateTimestamp:_groupId timeKeyValue:[[downLoadData objectForKey:@"cache"] objectForKey:@"timestamp"]];
                 [self BackClick];
                 
             }
             else
             {
                 [self BackClick];
             }
         }
         if (error)
         {
             if ([[error objectForKey:@"status"]integerValue] == 215) {
                 [PromptInfoView showMessage:@"姓名数据格式错误" superView:self];
             }
             else if ([[error objectForKey:@"status"]integerValue] == 208)
             {
                 [PromptInfoView showMessage:@"身份证格式错误" superView:self];
             }
             else
                 [PromptInfoView showMessage:[error objectForKey:@"info"] superView:self];
         }
         [MBProgressHUD hideHUDForView:self animated:YES];
     }
     ];
}


-(void)womanClick
{
    if (!womanBtn.enabled) {
        return;
    }
    if (womanBtn.selected) {
        manBtn.selected = YES;
        womanBtn.selected = NO;
        sexFlag = @"1";
        
    }
    else
    {
        manBtn.selected = NO;
        womanBtn.selected = YES;
        sexFlag = @"0";
    }
}

-(void)manClick
{
    if (!manBtn.enabled) {
        return;
    }
    if (manBtn.selected) {
        manBtn.selected = NO;
        womanBtn.selected = YES;
        sexFlag = @"0";
    }
    else
    {
        manBtn.selected = YES;
        womanBtn.selected = NO;
        sexFlag = @"1";
    }
}

-(void)BackClick
{
    if (_delegate && [_delegate respondsToSelector:@selector(addGuestInfoViewBackClick)]) {
        [_delegate addGuestInfoViewBackClick];
    }
}


-(void)hiddenKeyboard
{
    [self resignClick];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

//通过groupId来查询到时间戳
-(NSString *)getTimestamp:(NSString *)groupId
{
    GroupGuestLogic *groupGuestLogic = [[GroupGuestLogic alloc]init];
    return [groupGuestLogic queryGroupGuestTime:groupId];
}


//通过groupId来更新时间戳
-(void)updateTimestamp:(NSString *)groupId timeKeyValue:(NSString *)timeKeyValue
{
    GroupGuestLogic *groupGuestLogic = [[GroupGuestLogic alloc]init];
    [groupGuestLogic updateGroupGuestTime:groupId keyValue:timeKeyValue];
}
@end
